// pages/mall/detail/detail.js
const app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var spManger = require('../../data/ShopCartManager.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shouquanauthSetting: false,
    _showShareModel: false,
    _showhaibaoImage: '',
    _showhaibao: false,
    slefOptions: null,
    shouquan: false,
    stockNumStatus: false, // 商品是否售罄
    id: null, // 商品Id
    specsModalData: {},
    specsModal: false,
    MobileProductDetaiIndex: null, //商品主体
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    productHtml: '',
    shopName: '',
    choseStr: '', //已选择文字
    choseNum: 1, //选择那里的个数，这是页面的，不要和模板的混了
    unit: '', //选择那里的单位
    cartNum: 0,
    commentCounts:0
  },
  getCommentsCount:function(){
    var that = this;
    wx.request({
      //url: app.appSetting.host + "/api/MobileMall/index?ShopID=1AD227F46DFB1666",
      url: app.appSetting.host + "/api/Comment/GetCount?productId=" + this.data.MobileProductDetaiIndex.Id,
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.Code = 200 && res.data.Message == '') {
          that.setData({
            commentCounts: res.data.Data,
          })
        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none'
          })
        }
      }
    })

  },
  btnAddCartClick: function() {
    this.setData({
      'specsModalData.versionClick': false,
      'specsModalData.nowBuy': false
    })
    this.setData({
      specsModal: true,
    })
  },
  closeModal: function() {
    this.setData({
      specsModal: false
    });
  },

  aa() {},
  btnNowBuyClick: function() {
    this.setData({
      'specsModalData.versionClick': false,
      'specsModalData.nowBuy': true
    })
    //点击立即支付 冗余字段区分加车还是立即购买 specsModalData
    this.setData({
      specsModal: true,
    })
  },
  versionClick() {

    this.setData({
      specsModal: true,
    })
    this.setData({
      'specsModalData.versionClick': true,
      'specsModalData.nowBuy': false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    this.data.slefOptions = options;
    console.log(app.globalData.userInfo);

    app.initConfig().then(function (res) {
      if (res == 200) {
        that.checkLogin_getData(options);
      }

    })
    
    wx.getStorage({
      key: 'shopCart',
      success: function(res) {
        that.setData({
          cartNum: res.data.length
        });
      }

    })
  },
  //检测登录并获取商品信息
  checkLogin_getData: function(options) {
    let self = this;
    if (options.id) {
      wx.getStorage({
        key: 'seltUser',
        success: function(res) {
          if (app.globalData.userInfo == null)
            app.globalData.userInfo = res.data;
          self.getData(options); //获取商品信息
        },
        fail: function(res) {
          self.setData({
            shouquan: true
          });
        }
      })
    }
  },
  getData(options) {
    //wx.hideShareMenu();
    this.data.id = options.id;
    console.log(options);
    var that = this;
    wx.showLoading({
      title: '读取中 ',
    })
    wx.request({
      url: app.appSetting.host + "/api/Product/GetProductDetail?id=" + options.id + "&said=" + options.said,
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.Code = 200 && res.data.Message == '') {
          //初始化已选择文字
          var _choseStr = '';
          var _initAmountForMoreSku = 0; //如果是多规格，初始化当前默认规格属性下得价格，给选择框内初始化展示
          var _currentSelect_moresku = [0, 0, 0];
          if (res.data.Data.CurrentSkuType == 1) {
            _choseStr = res.data.Data.ProductName + ',';
          } else if (res.data.Data.CurrentSkuType == 2) {
            //默认取每个属性得第一个值。
            var propetyCombineId = '';
            var propetyList = res.data.Data.SkuManagerModel.Product_Sall_PropetyModelList;
            for (var i = 0; i < propetyList.length; i++) {

              if (i == propetyList.length - 1) {
                propetyCombineId += propetyList[i].Product_Sall_Propety_ValueList[0].Id;
                _choseStr += propetyList[i].Product_Sall_Propety_ValueList[0].PropetyValue + ',';
              } else {
                _choseStr += propetyList[i].Product_Sall_Propety_ValueList[0].PropetyValue + '+'
                propetyCombineId += propetyList[i].Product_Sall_Propety_ValueList[0].Id + '-'
              }



              //给初始化多规格属性值ID选择数组，赋值
              _currentSelect_moresku[i] = propetyList[i].Product_Sall_Propety_ValueList[0].Id;
            }
            console.log(_currentSelect_moresku);
            var skuModel = that.getSkuModelForMoreSku(res.data.Data.SkuManagerModel.MoreSkuModelList, propetyCombineId);
            res.data.Data.InitAmountForMoreSku = skuModel.SallPrice;
            res.data.Data.CurrentSelect_moresku = _currentSelect_moresku; //由于是模板传值，只能在模型中给值//多规格商品当前选择得规格属性//多规格商品当前选择得规格属性
            res.data.Data.CurrentStockNumForMoreSku = skuModel.StockNum; //多规格商品下，加载页面得SKU得库存
          }
          //初始化购买数量，由于是模板传值，只能在模型中给值
          res.data.Data.selecetdNum = 1;
          that.setData({
            MobileProductDetaiIndex: res.data.Data,
            shopName: app.globalData.userInfo.ShopName,
            choseStr: _choseStr,
            unit: res.data.Data.Unit
          })

          WxParse.wxParse('productHtml', 'html', res.data.Data.Detail, that, 5);
          that.getCommentsCount();//读取评价
        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none'
          })
        }
      }
    })



  },
  //通过组合属性ID，获取SKU模型
  getSkuModelForMoreSku: function(skuList, combineIds) {
    var res = null;
    for (var i = 0; i < skuList.length; i++) {
      if (combineIds == skuList[i].PropetyCombineId) {
        res = skuList[i];
        break;
      }
    }
    return res;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    console.log("点击分享");
    return {
      title: this.data.MobileProductDetaiIndex.Brand + ' ' + this.data.MobileProductDetaiIndex.ProductName,
      path: "pages/product/detail?id=" + this.data.id + "&said=" + app.appSetting.said,
      imageUrl: this.data.MobileProductDetaiIndex.BannerImgs[0],
    }
  },
  clickSku(ev) {
    let index = ev.currentTarget.dataset.index; //选中得是当前多i规格SKU属性数组得位置
    let propetyValueId = ev.currentTarget.dataset.propetyvalueid; //当前多规格SKU属性值的ID
    var _CurrentSelect_moresku = this.data.MobileProductDetaiIndex.CurrentSelect_moresku;
    _CurrentSelect_moresku[index] = propetyValueId;
    //计算出重新组合后的SKU的价格和库存
    var _currentPropetyalueCombineIds = _CurrentSelect_moresku.join('-').replace('-0', '').replace('-0', '');
    var _skuModel = this.getSkuModelForMoreSku(this.data.MobileProductDetaiIndex.SkuManagerModel.MoreSkuModelList, _currentPropetyalueCombineIds);
    console.log(_skuModel);
    //更改选择文字
    var _choseStr = _skuModel.ProppetyCombineName + ',';
    this.setData({
      'MobileProductDetaiIndex.CurrentSelect_moresku': _CurrentSelect_moresku,
      'MobileProductDetaiIndex.CurrentStockNumForMoreSku': _skuModel.StockNum,
      'MobileProductDetaiIndex.InitAmountForMoreSku': _skuModel.SallPrice,
      choseStr: _choseStr
    });

  },

  addNum(ev) {
    if (this.data.MobileProductDetaiIndex.CurrentSkuType == 1) {
      //单规格商品，库存判断
      if (this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.StockNum <= this.data.MobileProductDetaiIndex.selecetdNum) {
        wx.showToast({
          title: '库存不足',
          icon: 'none'
        })
        return
      }
    } else if (this.data.MobileProductDetaiIndex.CurrentSkuType == 2) {
      //多规格商品，库存判断
      //根据当前选择得多规格sku属性值ID数组，取出当前sku模型
      var _currentPropetyalueCombineIds = this.data.MobileProductDetaiIndex.CurrentSelect_moresku.join('-').replace('-0', '').replace('-0', '');
      var _skuModel = this.getSkuModelForMoreSku(this.data.MobileProductDetaiIndex.SkuManagerModel.MoreSkuModelList, _currentPropetyalueCombineIds);
      if (_skuModel.StockNum <= this.data.MobileProductDetaiIndex.selecetdNum) {
        wx.showToast({
          title: '库存不足',
          icon: 'none'
        })
        return
      }
    }
    var num = this.data.MobileProductDetaiIndex.selecetdNum + 1;
    this.setData({
      'MobileProductDetaiIndex.selecetdNum': num,
      choseNum: num
    });
  },
  decNum(ev) {
    if (this.data.MobileProductDetaiIndex.selecetdNum == 1) {
      return
    }
    var num = this.data.MobileProductDetaiIndex.selecetdNum - 1;
    this.setData({
      'MobileProductDetaiIndex.selecetdNum': num,
      choseNum: num
    });
  },
  goToGoodsList() {
    wx.navigateTo({
      url: "/pages/cart/cart/"
    });
  },
  showBuyDiv: function() {
    this.setData({
      specsModal: true
    });
  },
  nowBuy: function() {
    var model = {};
    model.ProductId = this.data.MobileProductDetaiIndex.Id;
    model.SaleNum = this.data.choseNum;
    var skuDetail = {};
    if (this.data.MobileProductDetaiIndex.CurrentSkuType == 1) {
      model.Product_SkuId = this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.Id;
      skuDetail.ProductId = this.data.MobileProductDetaiIndex.Id;
      skuDetail.Product_SkuId = this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.Id;
      skuDetail.ProductName = this.data.MobileProductDetaiIndex.ProductName;
      skuDetail.Brand = this.data.MobileProductDetaiIndex.Brand;
      skuDetail.SallPrice = this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.SallPrice;
      skuDetail.StockNum = this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.StockNum;
      skuDetail.ProppetyCombineName="";
      skuDetail.SkuType = 1;
      skuDetail.ImgPath = this.data.MobileProductDetaiIndex.BannerImgs[0];
      skuDetail.Weight = this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.Weight;
      skuDetail.ShippingTemplateId = this.data.MobileProductDetaiIndex.ShipTemplateId;
      model.SkuDetail = skuDetail;

    } else {
      var _currentPropetyalueCombineIds = this.data.MobileProductDetaiIndex.CurrentSelect_moresku.join('-').replace('-0', '').replace('-0', '');
      var _skuModel = this.getSkuModelForMoreSku(this.data.MobileProductDetaiIndex.SkuManagerModel.MoreSkuModelList, _currentPropetyalueCombineIds);
      model.Product_SkuId = _skuModel.Id;
      skuDetail.ProductId = this.data.MobileProductDetaiIndex.Id;
      skuDetail.Product_SkuId = _skuModel.Id;
      skuDetail.ProductName = this.data.MobileProductDetaiIndex.ProductName;
      skuDetail.Brand = this.data.MobileProductDetaiIndex.Brand;
      skuDetail.SallPrice = _skuModel.SallPrice;
      skuDetail.StockNum = _skuModel.StockNum;
      skuDetail.ProppetyCombineName = _skuModel.ProppetyCombineName;
      skuDetail.SkuType = 2;
      skuDetail.ImgPath = this.data.MobileProductDetaiIndex.BannerImgs[0];
      skuDetail.Weight = _skuModel.Weight;
      skuDetail.ShippingTemplateId = this.data.MobileProductDetaiIndex.ShipTemplateId;
      model.SkuDetail = skuDetail;
    }
    var sendModel = [];
    sendModel.push(model);
    wx.navigateTo({
      url: "/pages/order/order?carGoodsList=" + JSON.stringify(sendModel)+"&isnowbuy=1",
    })
  },

  saveCart() {
    var that = this;
    var model = {};
    model.ProductId = this.data.MobileProductDetaiIndex.Id;
    model.SaleNum = this.data.choseNum;

    //验证商品
    if (this.data.MobileProductDetaiIndex.CurrentSkuType == 1) {
      model.Product_SkuId = this.data.MobileProductDetaiIndex.SkuManagerModel.SingleSkuModel.Id;
    } else {
      var _currentPropetyalueCombineIds = this.data.MobileProductDetaiIndex.CurrentSelect_moresku.join('-').replace('-0', '').replace('-0', '');
      var _skuModel = this.getSkuModelForMoreSku(this.data.MobileProductDetaiIndex.SkuManagerModel.MoreSkuModelList, _currentPropetyalueCombineIds);
      model.Product_SkuId = _skuModel.Id;
    }
    model.State = 1; //是否选择
    model.SkuDetail = {};
    //从缓存取出购物车数据
    wx.getStorage({
      key: 'shopCart',
      success: function(res) {
        //判断购物车中是否已经存在当前sku,有得话，更改数量，没有push
        if (spManger.ShopCartManagerClass.Instance.IsExist(res.data, model.Product_SkuId)) {
          var skumodel = spManger.ShopCartManagerClass.Instance.GetModelBySkuId(res.data, model.Product_SkuId)
          skumodel.SaleNum = skumodel.SaleNum + model.SaleNum;
          res.data = spManger.ShopCartManagerClass.Instance.UpdateSkuModel(res.data, skumodel);
        } else {
          res.data.push(model);
        }
        wx.setStorage({
          key: 'shopCart',
          data: res.data,
          success: function(res) {
            wx.showToast({
              title: '加入购物车成功',
              icon: 'none',
              success: function() {
                var _cartnum = that.data.cartNum + that.data.choseNum;
                that.setData({
                  specsModal: false,
                  cartNum: _cartnum
                });
              }
            })
          }
        })
      },
      fail: function(res) {
        //不存在缓存
        var cartList = [];
        cartList.push(model);
        wx.setStorage({
          key: 'shopCart',
          data: cartList,
          success: function(res) {
            wx.showToast({
              title: '加入购物车成功',
              icon: 'none',
              success: function() {
                var _cartnum = that.data.cartNum + that.data.choseNum;
                that.setData({
                  specsModal: false,
                  cartNum: _cartnum
                });
              }
            })
          }
        })
      }
    })

  },

  getUserInfo: function(res) {
    let self = this;
    // 登录 
    wx.login({
      success: function(_res) {
        //获取用户信息
        wx.request({
          method: 'POST',
          url: app.appSetting.host + '/api/User/Login',
          data: {
            Spid: app.appSetting.spid,
            HeadImgUrl: res.detail.userInfo.avatarUrl,
            Sex: res.detail.userInfo.gender,
            NickName: res.detail.userInfo.nickName,
            Code: _res.code,
            AppType: 1
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function(result) {
            if (result.data.Code == 200 && result.data.Message == '') {
              app.globalData.userInfo = result.data.Data;
              wx.setStorage({
                key: 'seltUser',
                data: result.data.Data,
                success: function(res) {
                  self.setData({
                    shouquan: false
                  });
                  self.getData(self.data.slefOptions);
                }
              })
            } else {
              wx.showToast({
                title: result.data.Message,
                icon: 'none'
              })
            }
          },
          complete: function(res) {}
        })
      }
    });
  },
  //显示分享and生成海报
  showShareModel() {
    this.setData({
      _showShareModel: true,
    });
  },
  closeShowShareModel() {
    this.setData({
      _showShareModel: false,
    });
  },
  showhaibao() {
    wx.showLoading({
      title: '海报生成中...',
    })
    let self = this;
    wx.request({
      url: app.appSetting.host + "/api/product/MobileQrCodeImage",
      data: {
        ShopID: app.appSetting.spid,
        ProductImage: this.data.MobileProductDetaiIndex.BannerImgs[0],
        PECName: self.getNameStr( this.data.MobileProductDetaiIndex.ProductName),
        PriceRanage: this.data.MobileProductDetaiIndex.MinAmount == this.data.MobileProductDetaiIndex.MaxAmount ? this.data.MobileProductDetaiIndex.MinAmount : this.data.MobileProductDetaiIndex.MinAmount + "-"+this.data.MobileProductDetaiIndex.MaxAmount,
        ProductId: this.data.id
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.Code = 200 && res.data.Message == '') {
          self.setData({
            _showhaibaoImage: res.data.Data
          });
          self.setData({
            _showhaibao: true,
            _showShareModel: false,
          });

        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none'
          })
          that.setData({
            erroMsg: res.data.Message
          });
        }
      }
    })
    // this.setData({
    //   _showhaibao: true,
    //   _showShareModel: false,
    // });

  },
///截取字符串，如果超过指定长度，就...
  getNameStr:function(str){
      if(str.length>17)
          return str.substring(0,17)+"...";
      else
          return str
  },
  //保存图片
  saveImage() {
    let self = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.getSetting({
      success: function (res) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: function (res) {
            console.log("授权成功");
            //获取客户经理二维码图片
            console.log(self.data._showhaibaoImage);
            var imgUrl = self.data._showhaibaoImage; //图片地址
            wx.downloadFile({ //下载文件资源到本地，客户端直接发起一个 HTTP GET 请求，返回文件的本地临时路径
              url: imgUrl,
              success: function (res) {
                console.log(res); // 下载成功后再保存到本地
                wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath, //返回的临时文件路径，下载后的文件会存储到一个临时文件
                  success: function (res) {
                    console.log(res);
                    
                    wx.showModal({
                      title: '保存海报成功',
                      content: '商品海报已保存到手机相册，你可以分享到朋友圈了',
                      showCancel: false,
                      success: function (res) {
                        if (res.confirm) {
                          self.setData({
                            _showhaibao: false
                          });
                          wx.previewImage({
                            urls: [self.data._showhaibaoImage]
                            // 需要预览的图片http链接  使用split把字符串转数组。不然会报错
                          })
                        }
                      },
                      complete: function () {
                        wx.hideLoading();
                      }
                    })
                  }
                })
              },
              complete: function () {
                wx.hideLoading();
              }
            })
          },
          fail: function (res) {
            console.log("授权fail");
            console.log(res);
            self.setData({
              shouquanauthSetting: true,
              _showhaibao: false
            });
          },
          complete: function (res) {
            console.log(res)
            wx.hideLoading();

          }
        })
      }
    })
  },
  handler(e) {
    console.log(e);
    let that = this;
    // 对用户的设置进行判断，如果没有授权，即使用户返回到保存页面，显示的也是“去授权”按钮；同意授权之后才显示保存按钮
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '若不打开授权，则无法将图片保存在相册中！',
        showCancel: false
      })
      that.setData({
        shouquanauthSetting: false,
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '您已授权，赶紧将图片保存在相册中吧！',
        showCancel: false
      })
      that.setData({
        shouquanauthSetting: false,
      })
    }
  },
  closeshouquanauthSetting() {
    this.setData({
      shouquanauthSetting: false,
    });
  },
  showhaibaoModel() {
    this.setData({
      _showhaibao: false
    });
  }

})